package com.fh.common.interceptors;


import com.fh.utils.JWT;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/*   怎么实现一个拦截器
  *
  *
   * */
@Component // 将当前类交给ioc管理
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 获取令牌
        String token = request.getParameter("token");
        /* 没有令牌  拦截了 */
        if(StringUtils.isEmpty(token)){
            //设置响应数据的编码方式
            response.setCharacterEncoding("utf-8");
            //设置响应数据的类型
            response.setContentType("application/json");
            //设置响应内容
            PrintWriter writer = null;
            try {
                writer = response.getWriter();
            } catch (IOException e) {
                e.printStackTrace();
            }
            writer.write("{\"code\":100,\"msg\":\"没有token\"}");
            writer.close();
            return false;
        }
        //验证token
        Map unsign = JWT.unsign(token, Map.class);
        if(unsign==null){
            //设置响应数据的编码方式
            response.setCharacterEncoding("utf-8");
            //设置响应数据的类型
            response.setContentType("application/json");
            //设置响应内容
            PrintWriter writer = null;
            try {
                writer = response.getWriter();
            } catch (IOException e) {
                e.printStackTrace();
            }
            writer.write("{\"code\":100,\"msg\":\"非法token或者token已失效\"}");
            writer.close();
            return false;
        }
        return true;
    }
}
